package com.tansun.rule.config;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import com.tansun.ruledata.data.entity.DeployEnterpoint;
import com.tansun.ruledata.data.service.RuleProjectDeployService;
import com.tansun.ruledata.service.RuleDataCompileService;

/**
 * Copyright © 天阳宏业科技股份有限公司 - All Rights Reserved
 *
 * @description: 定时任务, 每隔30分钟进行入库解析
 * @author: renzeqian
 * @date: 2020-03-16 09:52
 **/
@RestController
@EnableScheduling
public class InitRuleTimer {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    private RuleDataCompileService ruleDataCompileService;
    
    @Autowired
    private  RuleProjectDeployService  ruleProjectDeployService;
    @Value("${offlineMode}")  
    private String offlineMode;
    
	//每天2点  0 0 2 * * ? 
//  每隔5秒执行一次：*/5 * * * * ?
//  每隔1分钟执行一次：0 */1 * * * ?
//  每天23点执行一次：0 0 23 * * ?
//  每天凌晨1点执行一次：0 0 1 * * ?
//  每月1号凌晨1点执行一次：0 0 1 1 * ?
//  每月最后一天23点执行一次：0 0 23 L * ?
//  每周星期天凌晨1点实行一次：0 0 1 ? * L
//  在26分、29分、33分执行一次：0 26,29,33 * * * ?
//  每天的0点、13点、18点、21点都执行一次：0 0 0,13,18,21 * * ?
    
    /**
     * 模拟定时任务
     * 定时表达式 : 每隔30分钟执行一次
     * long start = System.currentTimeMillis();
     * mainTimeController.cronJob1111();
     * long end = System.currentTimeMillis();
     * log.info("耗时:"+(end-start));
     *
     * @RequestMapping("/cronJob")
     */
    //@Scheduled(cron = "0 0/30 0-23 * * ? ")
    @Scheduled(cron = "0/30 * * * * ? ")
    public void cronJob1111() {
        try {
        	log.info("当前操作系统的名称：" + System.getProperty("os.name"));
    		log.info("当前Java 运行时环境版本：" + System.getProperty("java.version"));
    		log.info("当前Java 运行时环境供应商：" + System.getProperty("java.vendor"));
    		log.info("当前JVM字符集：" + System.getProperty("file.encoding"));//要确保编码为UTF-8
		 	StringBuffer   sqlBuf  = new  StringBuffer();
		 	if("0".equals(offlineMode) || StringUtils.isEmpty(offlineMode)) {
				return;
			}
		 	//总行定时加载
		 	if("2".equals(offlineMode)) {
//				sqlBuf.append("select * from rule_deployment rd left join rule_enterpoint re on rd.id=re.DEPLOYMENT_ID where rd.STATUS_IND='1' and re.control='on'");
//			   	List<Map<String,Object>> list =jdbcTemplate.queryForList(sqlBuf.toString(),new Object[]{});
//			   	 if (list != null){
//			   		 Map<String,String> initMapInfo = new HashMap<>();
//			   		 for (Map<String,Object> map :list){
//			   			String projectCode =(String) map.get("PROJECT_CODE");
//			   			String enterPoint = (String) map.get("CODE");
//			   			if(!initMapInfo.containsKey(projectCode)) {
//			   				initMapInfo.put(projectCode, enterPoint);
//			   			}else {
//			   				String enterPoints = initMapInfo.get(projectCode);
//			   				enterPoints += ";"+enterPoint;
//			   				initMapInfo.put(projectCode, enterPoints);
//			   			}
//			   		 }
//			   		 for (Entry<String, String> entry : initMapInfo.entrySet()) {
//			   			try {
//			   				ruleDataBusinessService.compileRuleData(entry.getKey(), entry.getValue());
//			   				log.info("rule_load_success 成功加载项目：" + entry.getKey() + ",入口调用编码："+entry.getValue());
//			   			} catch (Exception e) {
//			   				//log.error("异常加载项目：" + entry.getKey() + ",入口调用编码："+entry.getValue());
//			   				String error = ExceptionUtils.getStackTrace(e);
//			   				//log.error(error);
//			   				log.error("rule_load_exception 异常加载项目【rule_service】" + entry.getKey() + ",加载入口调用编码："+entry.getValue()+"异常;" + "message【"+error+"】");
//			   				continue;
//			   			}
//					}
//			
		 		List<DeployEnterpoint>  dpList  =  this.ruleProjectDeployService.findRuleExecDeployment();
			   	 if (dpList != null){
			   		 Map<String,String> initMapInfo = new HashMap<>();
			   		 for (DeployEnterpoint deployEnter :dpList){
			   			String projectCode = deployEnter.getProjectCode();
			   			String enterPoint = deployEnter.getCode() ;
			   			if(!initMapInfo.containsKey(projectCode)) {
			   				initMapInfo.put(projectCode, enterPoint);
			   			}else {
			   				String enterPoints = initMapInfo.get(projectCode);
			   				enterPoints += ";"+enterPoint;
			   				initMapInfo.put(projectCode, enterPoints);
			   			}
			   		 }
			   		for (Entry<String, String> entry : initMapInfo.entrySet()) {
			   			String projectCode =entry.getKey();
			   			String enterPoint = entry.getValue();
			   			try {
			   				ruleDataCompileService.prepareDataToCacheRuleExe(null, projectCode, enterPoint);
			   				log.info("成功加载项目：" + projectCode + ",入口调用编码："+enterPoint);
			   			} catch (Exception e) {
			   				log.error("异常加载项目：" + projectCode + ",入口调用编码："+enterPoint);
			   				String error = ExceptionUtils.getStackTrace(e);
			   				log.error(error);
			   				continue;
			   			}
			   		 }
			   	 }
		 	}else if("1".equals(offlineMode)) {
		 		//交行卡中心离线版
		 		List<DeployEnterpoint>  list  = this.ruleProjectDeployService.findRuleDeployment();
			   	 if (list != null){
			   		 Map<String,String> initMapInfo = new HashMap<>();
			   		 for (DeployEnterpoint deployEnterpoint :list){
			   			String projectCode =deployEnterpoint.getProjectCode();
			   			String enterPoint = deployEnterpoint.getCode();
			   			if(!initMapInfo.containsKey(projectCode)) {
			   				initMapInfo.put(projectCode, enterPoint);
			   			}else {
			   				String enterPoints = initMapInfo.get(projectCode);
			   				enterPoints += ";"+enterPoint;
			   				initMapInfo.put(projectCode, enterPoints);
			   			}
			   		 }
			   		for (Entry<String, String> entry : initMapInfo.entrySet()) {
			   			String projectCode =entry.getKey();
			   			String enterPoint = entry.getValue();
			   			try {
			   				//ruleDataCompileService.prepareDataToCache(null, projectCode, enterPoint);
			   				log.info("成功加载项目：" + projectCode + ",入口调用编码："+enterPoint);
			   			} catch (Exception e) {
			   				log.error("异常加载项目：" + projectCode + ",入口调用编码："+enterPoint);
			   				String error = ExceptionUtils.getStackTrace(e);
			   				log.error(error);
			   				continue;
			   			}
			   		 }
			   	 }
			}
        } catch (Exception e) {
			String error = ExceptionUtils.getStackTrace(e);
			log.error(error);
            log.error("InitRuleTimer={}", "【定时任务失败原因:】", e);
        }
    }
}
